package com.jzg.jcptadmin.presenter;

import android.os.Environment;
import android.text.TextUtils;

import com.jzg.jcptadmin.Utils.BitmapUtils;
import com.jzg.jcptadmin.Utils.ImgUtils;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.UpLoadImageData;
import com.jzg.jcptadmin.viewinterface.IQuickTaskUpdate;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @author: voiceofnet
 * email: pengkun@jingzhengu.com
 * phone:18101032717
 * @time: 2016/5/17 16:46
 * @desc:
 */
public class QuickTaskModifyPresenter extends BasePresenter<IQuickTaskUpdate> {
    private List<CarDetails.CarPicListEntity> identifyList;
    private List<CarDetails.CarPicListEntity> realList;
    private List<CarDetails.CarPicListEntity> moreList;
    private DataManager mDataManager;
    private String photoPath;
    private String thumPath;
    private File tempFile;//拍照的临时文件
    private CarDetails carDetails;
    private BaseActivity context;
    private AppContext appContext;
    private int picPositin;//照片的位置
    private int currRequestCode = 0;
    private IQuickTaskUpdate updateTask;
    private String makeId;
    private String modelId;
    private String[] identifyPhotoNames = {"行驶证", "登记证第1-2页", "登记证第3-4页"};
    private String[] realPhotoNames = {"左前45度角", "前排座椅", "里程表", "后排座椅", "中控台", "右后45度"};


    public QuickTaskModifyPresenter(BaseActivity context){
        this.context = context;
        mDataManager = DataManager.getInstance();
    }

    @Override
    public void attachView(IQuickTaskUpdate mvpView) {
        super.attachView(mvpView);
        this.updateTask = mvpView;
    }

    public  void initData(CarDetails carDetails){
        this.carDetails = carDetails;
        makeId = carDetails.getMakeId();
        modelId = carDetails.getModelId();
        tempFile = new File(Environment.getExternalStorageDirectory(), "/JZGErShouChe/temp.jpg");
        photoPath = Environment.getExternalStorageDirectory() + "/JZGErShouChe/photo_temp/";
        thumPath = Environment.getExternalStorageDirectory() + "/JZGErShouChe/photo_tub/";
        List<CarDetails.CarPicListEntity> carPicList = carDetails.getCarPicList();
        identifyList = new ArrayList<>();
        realList = new ArrayList<>();
        moreList = new ArrayList<>();
        identifyList = initPic(264,identifyPhotoNames);
        realList = initPic(267,realPhotoNames);
        if(carPicList!=null && carPicList.size()>0){
            for(CarDetails.CarPicListEntity item:carPicList){
                if(item.getItemId()<=266){
                    contains(identifyList, item);
                }else if(item.getItemId()<=272){
                    contains(realList, item);
                }else{
                    moreList.add(item);
                }
            }
            if(moreList.size()<9){
                CarDetails.CarPicListEntity newItem = new CarDetails.CarPicListEntity();
                moreList.add(newItem);
            }

        }
    }
    private List<CarDetails.CarPicListEntity> initPic(int start,String[] names){
        List<CarDetails.CarPicListEntity> resultList = new ArrayList<>();
        for(int i=0;i<names.length;i++){
            CarDetails.CarPicListEntity item = new CarDetails.CarPicListEntity();
            item.setItemId(start+i);
            item.setItemName(names[i]);
            resultList.add(item);
        }
        return resultList;
    }

    private void contains(List<CarDetails.CarPicListEntity> picList, CarDetails.CarPicListEntity item){
        for(CarDetails.CarPicListEntity it:picList){
            if(it.getItemId()==item.getItemId()){
                it.setItemName(item.getItemName());
                it.setItemId(item.getItemId());
                it.setId(item.getId());
                it.setPathBig(item.getPathBig());
                it.setItemName18(item.getItemName18());
                it.setPath(item.getPath());
            }
        }
    }

    /**
     * 从相机或者图库添加照片
     */
    public void addPic(final String picPath, final int requestCode) {
        Observable.create(new Observable.OnSubscribe<CarDetails.CarPicListEntity>() {
            @Override
            public void call(Subscriber<? super CarDetails.CarPicListEntity> subscriber) {
                //264-266认证照片三张，267-272实拍照片，273-281更多其他照片
                String bigPicPath = "";
                String tubPicPath = "";
                int fileNameIndex = 0;
                int start = 264;
                List<CarDetails.CarPicListEntity> currList = null;
                if (requestCode == Constant.REQ_CODE_PHOTO_INDETIFY) {
                    start = 264;
                    currList = identifyList;
                } else if (requestCode == Constant.REQ_CODE_PHOTO_REAL) {
                    start = 267;
                    currList = realList;
                } else if (requestCode == Constant.REQ_CODE_PHOTO_MORE) {
                    start = 273;
                    currList = moreList;
                }

                fileNameIndex = start + picPositin;
                bigPicPath = createPicPath(photoPath, fileNameIndex);
                tubPicPath = createPicPath(thumPath, fileNameIndex);
                if(fileNameIndex==267){
                    carDetails.setIconUrl(bigPicPath);
                }
                //保存大图
                BitmapUtils utils = new BitmapUtils();
                boolean isBigPicSave = utils.saveImage(picPath, bigPicPath);
                //保存缩略图
                boolean isTubPicSave = utils.saveImage(ImgUtils.getImageThumbnail(bigPicPath, ScreenUtils.dip2px(appContext, 60), ScreenUtils.dip2px(appContext, 40)), tubPicPath);
                fileNameIndex = fileNameIndex - start;
                CarDetails.CarPicListEntity item = null;
                if (isBigPicSave && isTubPicSave) {
                    item = currList.get(fileNameIndex);
                    item.setPathBig(bigPicPath);
                    item.setPath(tubPicPath);
                }
                if (requestCode == Constant.REQ_CODE_PHOTO_MORE && moreList.size() < 9) {
                    CarDetails.CarPicListEntity newItem = new CarDetails.CarPicListEntity();
                    currList.add(newItem);
                }
                subscriber.onNext(item);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()
        ).subscribe(new Action1<CarDetails.CarPicListEntity>() {
            @Override
            public void call(CarDetails.CarPicListEntity item) {
                upLoadImage(item,carDetails.getCarId(),String.valueOf(item.getItemId()));
            }
        });
    }


    public void upLoadImage(final CarDetails.CarPicListEntity item, String carid, String itemid) {
        updateTask.showDialog();
        if (appContext.isNetWork)
            mDataManager.UploadImage(item.getPathBig(), itemid, carid)
                    .observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<UpLoadImageData>() {
                        @Override
                        public void onCompleted() {
                            updateTask.dismissDialog();
                        }

                        @Override
                        public void onError(Throwable e) {

                            updateTask.onError("上传图片失败");
                            updateTask.dismissDialog();
                        }

                        @Override
                        public void onNext(UpLoadImageData upLoadImageData) {
                            updateTask.dismissDialog();
                            backByPhoto(upLoadImageData);
                        }
                    });
    }

    public void backByPhoto(UpLoadImageData data) {
        if (data.getStatus() == Constant.SUCCESS) {
            CarDetails.CarPicListEntity item = null;
            if (currRequestCode == Constant.REQ_CODE_PHOTO_INDETIFY) {
                item = identifyList.get(picPositin);
                item.setId(data.getPicId());
            } else if (currRequestCode == Constant.REQ_CODE_PHOTO_REAL) {
                item = realList.get(picPositin);
                item.setId(data.getPicId());
            } else if (currRequestCode == Constant.REQ_CODE_PHOTO_MORE) {
                item = moreList.get(picPositin);
                item.setId(data.getPicId());
            }
            updateTask.update(currRequestCode);
        } else {
            MyToast.showLong("上传图片失败");
        }
    }
    public String createPicPath(String dir, int pos) {
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(dirFile.getPath() + File.separator + pos + ".jpg");
        if (file.exists()) {
            file.delete();
        }
        return dirFile.getPath() + File.separator + pos + ".jpg";
    }

    public void submit(String vinCode,String brandSeries,String driveMode,String displacement,String gearBox,String firstRecordDate) {
        if(checkParams(vinCode,brandSeries,firstRecordDate)){
            Map<String, String> params = new HashMap<>();
            params.put("tokenid", "6");
            params.put("id", carDetails.getCarId());
            params.put("op", "save");
            params.put("Perf_DriveType", driveMode);//驱动形式
            params.put("TransmissionType", gearBox);//变速器类型
            params.put("Engine_Exhaust", displacement);//排气量
            params.put("MakeId", makeId);//品牌id
            params.put("ModelId", modelId);//车系ID
            params.put("RegDate", firstRecordDate);//初登日期
            params.put("VinCode", vinCode);//vin
            String picList = getPicList();
            params.put("imageList", picList);
            params.put("userId", appContext.getUser().getUserId() + "");
            Map<String, Object> params1 = new HashMap<>();
            params1.putAll(params);

            String sign = MD5Utils.getMD5Sign(params1);
            params.put("sign", sign);
            updateTask.showDialog();
            mDataManager.uploadQuickTaskData(params).
                    observeOn(AndroidSchedulers.mainThread()).
                    subscribeOn(Schedulers.io()).subscribe(new Subscriber<SuccessData>() {
                @Override
                public void onCompleted() {
                    updateTask.dismissDialog();
                }
                @Override
                public void onError(Throwable e) {
                    updateTask.dismissDialog();
                    updateTask.onError("修改任务失败");
                }

                @Override
                public void onNext(SuccessData successData) {
                    updateTask.dismissDialog();
                    int status = successData.getStatus();
                    if(status==100){
                        updateTask.onSuccess();
                    }else{
                        updateTask.onError(successData.getMsg());
                    }
                }
            });
        }
    }

    private String getPicList() {
        String picId = "";
        List<CarDetails.CarPicListEntity> list = new ArrayList<>();
        list.addAll(identifyList);
        list.addAll(realList);
        list.addAll(moreList);

        for (CarDetails.CarPicListEntity carPicListEntity : list) {
            if (carPicListEntity.getId() != 0) {
                picId = picId + carPicListEntity.getId() + ",";
            }
        }
        if (picId.length() > 0) {
            picId = picId.substring(0, picId.length() - 1);
        }
        return picId;
    }
    public boolean checkParams(String vinCode,String brandSeries,String firstRecordDate) {
        if(TextUtils.isEmpty(vinCode)){
            MyToast.showShort("请填写17位VIN码");
            return false;
        }
        if (vinCode.length() < 17) {
            MyToast.showShort("请正确填写17位VIN码");
            return false;
        }
        if(TextUtils.isEmpty(brandSeries)){
            MyToast.showShort("请选择品牌车系");
            return false;
        }
        if(TextUtils.isEmpty(firstRecordDate)){
            MyToast.showShort("请选择初登时间");
            return false;
        }
        for(CarDetails.CarPicListEntity item : realList){
            if(TextUtils.isEmpty(item.getPathBig())){
                MyToast.showShort("实车照片不全，请补全");
                return false;
            }
        }
        return true;
    }

    public File getTempFile() {
        return tempFile;
    }

    public void setTempFile(File tempFile) {
        this.tempFile = tempFile;
    }

    public List<CarDetails.CarPicListEntity> getIdentifyList() {
        return identifyList;
    }

    public void setIdentifyList(List<CarDetails.CarPicListEntity> identifyList) {
        this.identifyList = identifyList;
    }

    public List<CarDetails.CarPicListEntity> getRealList() {
        return realList;
    }

    public void setRealList(List<CarDetails.CarPicListEntity> realList) {
        this.realList = realList;
    }

    public List<CarDetails.CarPicListEntity> getMoreList() {
        return moreList;
    }

    public void setMoreList(List<CarDetails.CarPicListEntity> moreList) {
        this.moreList = moreList;
    }

    public int getPicPositin() {
        return picPositin;
    }

    public void setPicPositin(int picPositin) {
        this.picPositin = picPositin;
    }

    public AppContext getAppContext() {
        return appContext;
    }

    public void setAppContext(AppContext appContext) {
        this.appContext = appContext;
    }

    public int getCurrRequestCode() {
        return currRequestCode;
    }

    public void setCurrRequestCode(int currRequestCode) {
        this.currRequestCode = currRequestCode;
    }

    public String getMakeId() {
        return makeId;
    }

    public void setMakeId(String makeId) {
        this.makeId = makeId;
    }

    public String getModelId() {
        return modelId;
    }

    public void setModelId(String modelId) {
        this.modelId = modelId;
    }
}
